package com.cnb.servlet.v2.beans.factory.support;

import com.cnb.servlet.util.StrUtil;
import com.cnb.servlet.v2.beans.config.BeanDefinition;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

public class BeanDefinitionReader {

    private Properties configProperties = new Properties();

    private List<String> registryBeanClasses = new ArrayList<String>();

    public BeanDefinitionReader(String...location) {
        //加载配置文件
        doLoadConfig(location[0]);

        doScanner(configProperties.getProperty("scanPackage"));
    }

    public List<BeanDefinition> loadBeanDefinitions(){
        List<BeanDefinition> result = new ArrayList<BeanDefinition>();
        try{
            for (String registryBeanClass : this.registryBeanClasses) {
                Class<?> aClass = Class.forName(registryBeanClass);
                if(aClass.isInterface()){continue;}
                result.add(doCreateBeanDefinition(StrUtil.toLowerCaseFirst(aClass.getSimpleName()),aClass.getName()));

                for (Class<?> anInterface : aClass.getInterfaces()) {
                    String allName = anInterface.getName();
                    result.add(doCreateBeanDefinition(allName,aClass.getName()));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 创建BeanDefinition对象
     * @param simpleName
     * @param name
     * @return
     */
    private BeanDefinition doCreateBeanDefinition(String simpleName, String name) {
        BeanDefinition beanDefinition = new BeanDefinition();
        beanDefinition.setFactoryClassName(name);
        beanDefinition.setFactoryName(simpleName);
        return beanDefinition;
    }

    /**
     * 加载配置文件
     * @param contextConfigLocation 配置文件所在的路径
     */
    private void doLoadConfig(String contextConfigLocation) {

        try(InputStream stream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);){
            configProperties.load(stream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 扫描包
     * @param scanPackage 需要扫描的包
     * @deprecated 扫描该下面的所有class文件，将其全限定类名加入到集合里面
     */
    private void doScanner(String scanPackage) {
        URL resourcePath = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File scanPath = new File(resourcePath.getPath());
        for (File itemFile : scanPath.listFiles()) {
            if(itemFile.isDirectory()){
                doScanner(scanPackage + "." + itemFile.getName());
            }else{
                if(!itemFile.getName().endsWith(".class")){continue;}
                String classAllName = scanPackage + "." + itemFile.getName().replaceAll(".class","");
                registryBeanClasses.add(classAllName);
            }
        }
    }

}
